import { followCancel, followAccept, followReject, followRequest } from '@/api/user'
import { FollowStatus } from '@/enums'
interface FollowMapping {
	textT: string // 按钮文字
	api: (payload: any) => Promise<any> // 请求接口函数
	statuses: FollowStatus[] // 状态条件
	isRequestPage?: boolean // 可选条件，是否在申请页面
}

const FollowStatusMapping: FollowMapping[] = [
	{
		textT: 'follow.following',
		api: followRequest,
		statuses: [FollowStatus.None],
		isRequestPage: true
	},
	{
		textT: 'follow.following',
		api: followRequest,
		statuses: [
			FollowStatus.RequestedByThem,
			FollowStatus.RejectedByMe,
			FollowStatus.RejectedByThem,
			FollowStatus.MutualRequestRejectedByMe,
			FollowStatus.MutualRequestRejectedByThem,
			FollowStatus.MutualRequestRejected
		]
	},
	{
		textT: 'follow.withdrawApplication',
		api: followCancel,
		statuses: [
			FollowStatus.RequestedByMe,
			FollowStatus.MutualRequest,
			FollowStatus.MutualRequestFollowedByThem
		]
	},
	{
		textT: 'follow.accept',
		api: followAccept,
		statuses: [
			FollowStatus.RequestedByThem,
			FollowStatus.MutualRequest,
			FollowStatus.MutualRequestFollowedByMe
		],
		isRequestPage: true
	},
	{
		textT: 'follow.reject',
		api: followReject,
		statuses: [
			FollowStatus.RequestedByThem,
			FollowStatus.MutualRequest,
			FollowStatus.MutualRequestFollowedByMe
		],
		isRequestPage: true
	},
	{
		textT: 'follow.unfollow',
		api: followCancel,
		statuses: [FollowStatus.FollowedByMe, FollowStatus.MutualRequestFollowedByMe]
	},
	{
		textT: 'follow.followBack',
		api: followRequest,
		statuses: [FollowStatus.FollowedByThem, FollowStatus.MutualRequestFollowedByThem]
	},
	{
		textT: 'follow.bothFollowed',
		api: followCancel,
		statuses: [FollowStatus.MutualFollow]
	}
]

// 获取匹配的操作项
export function getFollowAction(
	currentStatus: FollowStatus,
	isRequestPage: boolean = false
): FollowMapping | undefined {
	console.log('currentStatus', currentStatus)
	return FollowStatusMapping.find((mapping) => {
		// 匹配状态和页面条件
		return (
			mapping.statuses.includes(currentStatus) &&
			(mapping.isRequestPage === undefined || mapping.isRequestPage === isRequestPage)
		)
	})
}

// 调用对应的接口
export async function handleFollowAction(
	currentStatus: FollowStatus,
	payload: any, // 请求参数
	isRequestPage: boolean = false
): Promise<void> {
	const action = getFollowAction(currentStatus, isRequestPage)
	if (action) {
		try {
			// 直接调用接口函数
			await action.api(payload)
		} catch (error) {
			console.error(error)
		}
	}
}
